﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Plugins
{
    public partial class FormSettings : Form
    {
        private bool autostart;
        private bool isAdministrator;
        private string key = @"Software\Microsoft\Windows\CurrentVersion\Run";
        private string name = "Plugins";
        private object value = Application.ExecutablePath + " autostart";
        public FormSettings()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            isAdministrator = CheckAdministrator();
            autostart = CheckAutoStart();
            btnAutoStart.Text = autostart ? "取消开机自启" : "允许开机自启";
        }

        private bool CheckAdministrator()
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }

        private bool CheckAutoStart()
        {
            if (!isAdministrator)
                return false;
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey rk2 = rk.CreateSubKey(key);
            object value = rk2.GetValue(name);
            return value.ToString()== this.value.ToString();
        }
        private void btnAutoStart_Click(object sender, EventArgs e)
        {
            if (!isAdministrator)
            {
                MessageBox.Show("请以管理员身份运行本程序");
                return;
            }
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey rk2 = rk.CreateSubKey(key);
            if (!autostart)
            {
                rk2.SetValue(name, value);
                rk2.Close();
                rk.Close();
                autostart = true;
                btnAutoStart.Text = autostart ? "取消开机自启" : "允许开机自启";
                MessageBox.Show("已设置开机自启");
            }
            else
            {
                rk2.DeleteValue(name);
                rk2.Close();
                rk.Close();
                autostart = false;
                btnAutoStart.Text = autostart ? "取消开机自启" : "允许开机自启";
                MessageBox.Show("已取消开机自启");
            }
        }
    }
}
